package online.keepon.wechatpush.service;

import com.nlf.calendar.Lunar;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUserList;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import online.keepon.wechatpush.config.WechatProperties;
import online.keepon.wechatpush.model.Dialogue;
import online.keepon.wechatpush.model.Weather;
import online.keepon.wechatpush.utils.DateUtil;
import online.keepon.wechatpush.utils.TianApiUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @author top
 */
@Slf4j
@Component
public class TemplateMsgService {

    @Autowired
    private WechatProperties wechatProperties;
    @Autowired
    private TianApiUtil apiUtil;

    private WxMpService wxMpService;

    @PostConstruct
    public void wxTemplateMsgService() {
        WxMpDefaultConfigImpl wxStorage = new WxMpDefaultConfigImpl();
        wxStorage.setAppId(wechatProperties.getAppId());
        wxStorage.setSecret(wechatProperties.getSecret());
        wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(wxStorage);
    }


    public void push() {
        WxMpTemplateMessage templateMessage = templateMessage();
        WxMpTemplateMsgService templateMsgService = wxMpService.getTemplateMsgService();
        try {
            //发送到对应用户的openId
            templateMessage.setToUser(wechatProperties.getOpenId());
            templateMsgService.sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error("消息推送失败: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 推送给多个用户
     */
    public void push(List<String> openIds) {
        WxMpTemplateMessage templateMessage = templateMessage();
        WxMpTemplateMsgService templateMsgService = wxMpService.getTemplateMsgService();
        try {
            //发送到对应用户的openId
            if (!openIds.isEmpty()) {
                for (String openId : openIds) {
                    templateMessage.setToUser(openId);
                    templateMsgService.sendTemplateMsg(templateMessage);
                }
            }
        } catch (WxErrorException e) {
            log.error("消息推送失败: {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取所有用户openId
     */
    public List<String> openIds() {
        WxMpUserService userService = wxMpService.getUserService();
        try {
            WxMpUserList wxMpUserList = userService.userList();
            return wxMpUserList.getOpenids();
        } catch (WxErrorException e) {
            log.error("获取用户openId 失败 {}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 模板消息
     */
    public WxMpTemplateMessage templateMessage() {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .templateId(wechatProperties.getTemplateId())
                .build();
        templateMessage.setData(templateData());
        log.info("推送消息： {}", templateMessage.toJson());
        return templateMessage;
    }

    /**
     * 填充模板数据
     */
    public List<WxMpTemplateData> templateData() {
        List<WxMpTemplateData> dataList = new ArrayList<>();
        //彩虹屁
        WxMpTemplateData wxMpTemplateData = new WxMpTemplateData("rainbow", apiUtil.getRainbow(), "#FF69B4");
        // 天气信息
        Weather weather = apiUtil.getWeather();
        if (weather != null) {
            dataList.add(new WxMpTemplateData("remark", "♥♥♥♥♥"));
            dataList.add(new WxMpTemplateData("date", DateUtil.formatDate(weather.getDate())));
            Lunar lunar = Lunar.fromDate(weather.getDate());
            String lunarLabel = "农历" + lunar.getMonthInChinese() + lunar.getDayInChinese();
            String festival = String.join(",", lunar.getFestivals());
            dataList.add(new WxMpTemplateData("lunar", lunarLabel, "#00BFFF"));
            dataList.add(new WxMpTemplateData("festival", festival, "#00BFFF"));
            dataList.add(new WxMpTemplateData("week", weather.getWeek()));
            dataList.add(new WxMpTemplateData("province", weather.getProvince()));
            dataList.add(new WxMpTemplateData("area", weather.getArea()));
            dataList.add(new WxMpTemplateData("areaid", weather.getAreaid()));
            dataList.add(new WxMpTemplateData("weather", weather.getWeather(), "#00FFFF"));
            dataList.add(new WxMpTemplateData("weatherimg", weather.getWeatherimg()));
            dataList.add(new WxMpTemplateData("weathercode", weather.getWeathercode()));
            dataList.add(new WxMpTemplateData("real", weather.getReal()));
            dataList.add(new WxMpTemplateData("lowest", weather.getLowest(), "#173177"));
            dataList.add(new WxMpTemplateData("highest", weather.getHighest(), "#FF6347"));
            dataList.add(new WxMpTemplateData("wind", weather.getWind(), "#EE212D"));
            dataList.add(new WxMpTemplateData("windspeed", weather.getWindspeed()));
            dataList.add(new WxMpTemplateData("windsc", weather.getWindsc(), "#EE212D"));
            dataList.add(new WxMpTemplateData("sunrise", weather.getSunrise()));
            dataList.add(new WxMpTemplateData("sunset", weather.getSunset()));
            dataList.add(new WxMpTemplateData("moonrise", weather.getMoonrise()));
            dataList.add(new WxMpTemplateData("moondown", weather.getMoondown()));
            dataList.add(new WxMpTemplateData("pcpn", weather.getPcpn()));
            dataList.add(new WxMpTemplateData("uv_index", weather.getUv_index()));
            dataList.add(new WxMpTemplateData("aqi", weather.getAqi()));
            dataList.add(new WxMpTemplateData("quality", weather.getQuality()));
            dataList.add(new WxMpTemplateData("vis", weather.getVis()));
            dataList.add(new WxMpTemplateData("humidity", weather.getHumidity()));
            dataList.add(new WxMpTemplateData("tips", weather.getTips()));
            // 经典台词
            Dialogue dialogue = apiUtil.getDialogue();
            if (dialogue != null) {
                dataList.add(new WxMpTemplateData("dialogue", dialogue.getDialogue()));
                dataList.add(new WxMpTemplateData("english", dialogue.getEnglish()));
                dataList.add(new WxMpTemplateData("source", dialogue.getSource()));
                String type = dialogue.getType() == 1 ? "华语" : "外语";
                dataList.add(new WxMpTemplateData("type", type));
            }
        }
        dataList.add(wxMpTemplateData);
        return dataList;
    }
}
